<!--  -->
<template>
  <div class="filingInfo">
    <div class="formList">
      <div class="group">
        <div class="itemGroup">
          <label class="itemName">报备人姓名：</label>
          <input
            class="itemInput"
            v-model="reportState.form.registrarName"
            type="text"
            placeholder="请输入报备人姓名"
          />
        </div>
        <div class="itemGroup">
          <label class="itemName">项目名称：</label>
          <el-select
            class="sheetPlatform"
            disabled
            v-model="projectState.projectId"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectSelectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!--          <div class="plateTips">（采购人进行采购的平台）</div>-->
        </div>
      </div>
      <div class="group">
        <div class="itemGroup">
          <label class="itemName">报备人电话：</label>
          <input
            class="itemInput"
            v-model="reportState.form.registrarPhone"
            type="text"
            placeholder="请输入报备人电话"
          />
        </div>
        <div class="itemGroup dateGroup">
          <label class="itemName">项目报备时间：</label>
          <div class="dateBox">
            <span>今天</span>
            <span class="to">至</span>
            <el-date-picker
              v-model="reportState.form.registrarEndTime"
              :picker-options="{disabledDate: disabledEndDate}"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </div>
          <div class="timeTips">（报备周期选择今日起7天内）</div>
        </div>
      </div>
      <div class="group">
        <div class="itemGroup">
          <label class="itemName">采购单位（全称）：</label>
          <input
            class="itemInput"
            v-model="reportState.form.purchaseCompany"
            type="text"
            placeholder="请输入采购单位"
          />
        </div>
        <div class="itemGroup">
          <label class="itemName">收货人：</label>
          <input
            class="itemInput"
            v-model="reportState.form.consigneeName"
            type="text"
            placeholder="请输入收货人"
          />
        </div>
      </div>
      <div class="group groupAddr">
        <div class="itemGroup">
          <label class="itemName">收货地址：</label>
          <el-select
            class="sheetPlatform"
            v-model="reportState.form.deliveryProvinceName"
            placeholder="请选择"
            @change="provinceChange"
          >
            <el-option
              v-for="prov in province"
              :key="prov.code"
              :label="prov.name"
              :value="prov.name"
            ></el-option>
          </el-select>
          <el-select
            class="sheetPlatform"
            v-model="reportState.form.deliveryCityName"
            style="width:120px;"
            placeholder="请选择"
            @change="cityChange"
          >
            <el-option
              v-for="item in city"
              :label="item.name"
              :value="item.name"
              :key="item.code"
            ></el-option>
          </el-select>
          <el-select
            class="sheetPlatform"
            :value="reportState.form.deliveryDistrictName"
            @input="$set(reportState.form, 'deliveryDistrictName', $event)"
            style="width:120px;"
            placeholder="请选择"
            @change="areaChange"
          >
            <el-option
              v-for="area in addrData.area"
              :key="area.code"
              :value="area.name"
              :label="area.name"
            ></el-option>
          </el-select>
          <textarea
            class="addrDetail"
            v-model="reportState.form.deliveryFullAddress"
            placeholder="详细地址,街道,门牌等"
          ></textarea>
          <div class="tips">（收货地址尽量详细填写，请至少精确到省、市、区县）</div>
        </div>
      </div>
      <div class="group groupAddr">
        <div class="itemGroup">
          <label class="itemName remaskName">备注：</label>
          <textarea
            class="remasks"
            v-model="reportState.form.remark"
            placeholder="请输入备注信息,限100字"
            maxlength="100"
          ></textarea>
        </div>
      </div>
      <div class="group clearGroup">
        <el-button class="filing-button" @click="clearInfo">清 空</el-button>
        <!-- <div class="clearBtn" @click="clearInfo">清空</div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, getCurrentInstance, ref, watchEffect } from '@vue/composition-api'
import { useReport } from '@/hooks/report'
import { useProjectCustomerSetting, useProjectList } from '@/hooks/project'

export default defineComponent({
  // import引入的组件需要注入到对象中才能使用
  setup () {
    const vm = getCurrentInstance()
    const validateForm = async () => {
      return new Promise(resolve => {
        console.log(vm.mustIsEmpty())
        resolve(vm.mustIsEmpty())
      })
    }
    const { reportState } = useReport(validateForm)

    const disabledEndDate = date => {
      const now = Date.now()
      const time = date.getTime()
      const dayTime = 60 * 60 * 24 * 1000
      return now > time || now + dayTime * 7 < time
    }

    const areaCodeList = ref([])

    const { projectSelectOption, state: projectState } = useProjectCustomerSetting()
    const projectList = useProjectList()
    watchEffect(() => {
      if (projectList.value.length > 0 && projectState.projectId) {
        const project = projectList.value.find(item => item.projectId === projectState.projectId)
        areaCodeList.value = project.areaCodeList
      }
    })

    return {
      reportState,
      disabledEndDate,
      projectSelectOption,
      projectState,
      areaCodeList,
    }
  },
  data () {
    // 这里存放数据
    return {
      // 提交的数据
      submitData: {
        registrarName: '', // 报备人姓名
        projectId: '', // 点单平台id
        purchasePlatformName: '', // 点单平台
        registrarPhone: '', // 报备人电话
        registrarStartTime: '', // 报备开始时间
        registrarEndTime: '', // 报备结束时间
        purchaseCompany: '', // 采购单位
        consigneeName: '', // 收货人
        remark: '', // 备注
        deliveryCityCode: '', // 收货地址市区代码
        deliveryCityName: '', // 收货地址市区名称
        deliveryDistrictCode: '', // 收货地址区/县代码
        deliveryDistrictName: '', // 收货地址区/县名称
        deliveryProvinceCode: '', // 收货地址省份代码
        deliveryProvinceName: '', // 收货地址省份名称
        deliveryFullAddress: '', // 收货完整地址
      },
      // 地址数据
      addrData: {
        province: [],
        city: [],
        area: [],
      },
    }
  },
  mounted () {
    // 返回当前页或刷新 获取报备人信息
    this.getAddress(0)
      .then(async () => {
        const { deliveryProvinceName, deliveryCityName, deliveryDistrictName } = this.reportState.form
        if (deliveryProvinceName) {
          await this.provinceChange(this.reportState.form.deliveryProvinceName)
          await this.cityChange(deliveryCityName)
          this.areaChange(deliveryDistrictName)
        }
      })
  },
  // 方法集合
  methods: {

    // 清空输入信息
    clearInfo () {
      this
        .$confirm('确定要清空所有信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          Object.keys(this.submitData).forEach(key => {
            this.$set(this.reportState.form, key, '')
          })
          this.$message({
            message: '数据清除成功',
            type: 'success',
          })
        })
        .catch(() => {})
    },
    /**
     * 获取全国省直辖市信息
     * param {id} 默认id = 0
     */
    getAddress (id) {
      return this.$axios
        .get('api/createFilingMessage/getAddressInfo?id=' + id)
        .then(resp => {
          this.$set(this.addrData, 'province', resp.result)
        })
    },
    // 省 切换
    provinceChange (name) {
      const id = this.getAccessPlace(this.addrData.province, name)
      this.reportState.form.deliveryProvinceName = name
      this.reportState.form.deliveryProvinceCode = id
      this.reportState.form.deliveryCityCode = ''
      this.reportState.form.deliveryCityName = ''
      this.reportState.form.deliveryDistrictCode = ''
      this.reportState.form.deliveryDistrictName = ''
      this.reportState.form = {
        ...this.reportState.form,
      }
      return this.getCityData(id)
    },
    /**
     * 获取城市市信息
     * param {id} 默认id
     */
    getCityData (id) {
      return this.$axios
        .get('api/createFilingMessage/getAddressInfo?id=' + id)
        .then(resp => {
          this.addrData.city = resp.result
        })
    },
    // 城市切换
    cityChange (name) {
      const id = this.getAccessPlace(this.addrData.city, name)
      this.reportState.form.deliveryCityName = name
      this.reportState.form.deliveryCityCode = id
      this.reportState.form.deliveryDistrictCode = ''
      this.reportState.form.deliveryDistrictName = ''
      this.reportState.form = {
        ...this.reportState.form,
      }
      return this.gerAreaData(id)
    },
    /**
     * 获取市区信息
     * param {id} 默认id
     */
    gerAreaData (id) {
      return this.$axios
        .get('api/createFilingMessage/getAddressInfo?id=' + id)
        .then(resp => {
          this.addrData.area = resp.result
        })
    },
    // 地区切换
    areaChange (name) {
      const id = this.getAccessPlace(this.addrData.area, name)
      this.reportState.form.deliveryDistrictName = name
      this.reportState.form.deliveryDistrictCode = id
      this.reportState.form = {
        ...this.reportState.form,
      }
    },

    // 通过城市名字获取城市id
    getAccessPlace (obj, name) {
      const pro = obj.find(item => {
        if (item.name == name) {
          return item
        }
      })
      return pro.code
    },
    // 必填项验证
    mustIsEmpty () {
      let flag = false
      for (const item in this.submitData) {
        console.log('item', item, this.reportState.form[item])
        if (
          item != 'registrarStartTime' &&
          item != 'remark' &&
          item != 'deliveryCityName' &&
          item != 'deliveryDistrictName' &&
          item != 'deliveryProvinceName' &&
          item != 'projectId' &&
          item != 'purchasePlatformName'
        ) {
          if (this.reportState.form[item]) {
            flag = true
          } else {
            this.$alert('还有信息未填写，请填写完后再进行下一步')
            flag = false
            return false
          }
        }
      }

      return flag
    },

  },
  computed: {
    province () {
      const list = this.addrData.province.filter(item => this.areaCodeList.indexOf(~~item.code) > -1)
      return list.length > 0 ? list : this.addrData.province
    },
    city () {
      const list = this.addrData.city.filter(item => this.areaCodeList.indexOf(~~item.code) > -1)
      return list.length > 0 ? list : this.addrData.city
    },
  },
})
</script>
<style lang='less' scoped>
@themeColor:#298DF8;
.filingInfo {
  padding-left: 80px;
  .group {
    display: flex;
    // align-items: center;
    .itemGroup {
      display: flex;
      align-items: center;
      margin-bottom: 45px;
      position: relative;
      width: 50%;
      .itemName {
        display: block;
        font-size: 14px;
        font-weight: 500;
        width: 148px;
        margin-right: 5px;
        text-align: right;
        font-weight: bold;
        &:before {
          display: inline-block;
          content: "*";
          color: #e51c23;
        }
      }
      .itemInput {
        width: 204px;
        height: 30px;
        border-radius: 5px;
        background: #fff;
        border: 1px solid #ccc;
        padding: 0 5px;
      }
      /deep/ .el-select,
      /deep/ .el-input,
      /deep/ .el-input__inner {
        height: 30px;
        font-size: 14px;
        border-color: #ccc;
      }
      /deep/ .el-input__icon {
        line-height: 30px;
      }
      .addrDetail {
        resize: none;
        border-radius: 5px;
        border: 1px solid #ccc;
        width: 214px;
        height: 64px !important;
      }
      .remasks {
        resize: none;
        border-radius: 5px;
        width: 675px;
        height: 64px !important;
        padding: 5px;
        border: 1px solid #ccc;
      }
      .tips,
      .plateTips,
      .timeTips {
        position: absolute;
        bottom: 0;
        left: 150px;
        font-size: 12px;
        color: #e51c23;
      }
      .plateTips,
      .timeTips {
        bottom: -18px;
      }
    }
  }
  .groupAddr {
    .itemGroup {
      width: 100%;
      .sheetPlatform {
        width: 160px;
        margin-right: 20px;
      }
      .remaskName {
        &:before {
          display: none;
        }
      }
    }
  }
  .dateGroup {
    .dateBox {
      display: flex;
      align-items: center;
      span {
        display: block;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        border: 1px solid #dcdfe6;
        padding: 0 12px;
        border-radius: 5px 0 0 5px;
      }
      .to {
        padding: 0 5px;
        border-left: none;
        border-right: none;
        border-radius: 0;
      }
      /deep/ .el-input__inner {
        width: 130px;
        border-radius: 0 5px 5px 0;
        padding-right: 10px;
      }
      /deep/ .el-input__suffix {
        right: 65px;
      }
    }
  }
  .clearGroup {
    width: 90%;
    justify-content: flex-end;
    padding-right: 14px;
    .filing-button {
      width: 80px;
      height: 30px;
      line-height: 30px;
      background: #fff;
      color: @themeColor;
      font-size: 14px;
      text-align: center;
      border: 1px solid @themeColor;
      border-radius: 0;
      cursor: pointer;
    }
  }
}
</style>
